const vscode = require('vscode');
const path = require('path');
const fs = require('fs').promises;

/**
 * MCP配置界面的WebView提供器
 */
class McpViewProvider {
    /**
     * 视图类型标识符
     */
    static viewType = 'mcp.configView';
    
    constructor(extensionUri, mcpService) {
        this._extensionUri = extensionUri;
        this._mcpService = mcpService;
        this._view = undefined;
    }

    /**
     * 解析WebView视图
     */
    resolveWebviewView(
        webviewView,
        _context,
        _token
    ) {
        this._view = webviewView;

        // 配置WebView
        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [this._extensionUri]
        };

        // 设置WebView内容
        webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

        // 处理WebView消息
        this._setWebviewMessageListener(webviewView.webview);

        // 初始化视图数据
        this._initViewData();
    }

    /**
     * 获取WebView的HTML内容
     */
    _getHtmlForWebview(webview) {
        // 获取资源路径
        const scriptUri = webview.asWebviewUri(
            vscode.Uri.joinPath(this._extensionUri, 'media', 'mcp', 'main.js')
        );
        const styleUri = webview.asWebviewUri(
            vscode.Uri.joinPath(this._extensionUri, 'media', 'mcp', 'styles.css')
        );

        // 生成HTML
        return `<!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>MCP配置</title>
            <link href="${styleUri}" rel="stylesheet">
        </head>
        <body>
            <div class="container">
                <h1>MCP服务器管理</h1>
                
                <div class="actions">
                    <button id="add-server" class="button">添加服务器</button>
                    <button id="refresh" class="button">刷新</button>
                    <button id="back-to-chat" class="button">返回聊天</button>
                </div>
                
                <div class="servers-container">
                    <h2>已连接的MCP服务器</h2>
                    <div id="servers-list" class="list">
                        <div class="loading">正在加载...</div>
                    </div>
                </div>
                
                <div class="tools-container">
                    <h2>可用的MCP工具</h2>
                    <div id="tools-list" class="list">
                        <div class="loading">选择服务器查看工具</div>
                    </div>
                </div>
            </div>
            
            <script src="${scriptUri}"></script>
        </body>
        </html>`;
    }

    /**
     * 设置WebView消息监听器
     */
    _setWebviewMessageListener(webview) {
        webview.onDidReceiveMessage(async (message) => {
            switch (message.command) {
                case 'getServers':
                    this._getServers();
                    break;
                    
                case 'getServerTools':
                    this._getServerTools(message.serverName);
                    break;
                    
                case 'addServer':
                    this._addServer();
                    break;
                    
                case 'deleteServer':
                    this._deleteServer(message.serverName);
                    break;
                    
                case 'toggleServer':
                    this._toggleServer(message.serverName, message.enabled);
                    break;
                    
                case 'toggleToolAutoApprove':
                    this._toggleToolAutoApprove(message.serverName, message.toolNames, message.autoApprove);
                    break;
                    
                case 'updateServerTimeout':
                    this._updateServerTimeout(message.serverName, message.timeout);
                    break;
                    
                case 'openConfig':
                    vscode.commands.executeCommand('mcp.openConfig');
                    break;
            }
        });
    }

    /**
     * 初始化视图数据
     */
    async _initViewData() {
        if (!this._view) {
            return;
        }

        // 获取服务器列表
        try {
            console.log('初始化MCP视图数据...');
            if (!this._mcpService) {
                console.error('MCP服务未初始化');
                this._view.webview.postMessage({
                    command: 'error',
                    message: 'MCP服务未初始化，请重新启动VS Code'
                });
                return;
            }
            
            const servers = this._mcpService.getServers();
            console.log('获取到服务器列表:', servers);
            this._view.webview.postMessage({
                command: 'serversData',
                servers
            });
            
            // 注册状态更新命令
            vscode.commands.registerCommand('mcp.updateStatus', (message) => {
                if (this._view && this._view.webview) {
                    console.log('通过命令接收MCP状态更新:', message);
                    this._view.webview.postMessage(message);
                }
            });
        } catch (error) {
            console.error('获取MCP服务器列表失败:', error);
            this._view.webview.postMessage({
                command: 'error',
                message: `获取服务器列表失败: ${error instanceof Error ? error.message : String(error)}`
            });
        }
    }

    /**
     * 获取服务器列表
     */
    _getServers() {
        if (!this._view) {
            return;
        }

        try {
            const servers = this._mcpService.getServers();
            this._view.webview.postMessage({
                command: 'serversData',
                servers
            });
        } catch (error) {
            console.error('获取MCP服务器列表失败:', error);
            this._view.webview.postMessage({
                command: 'error',
                message: `获取服务器列表失败: ${error instanceof Error ? error.message : String(error)}`
            });
        }
    }

    /**
     * 获取服务器的工具列表
     */
    _getServerTools(serverName) {
        if (!this._view) {
            return;
        }

        try {
            const tools = this._mcpService.getServerTools(serverName);
            this._view.webview.postMessage({
                command: 'serverToolsData',
                serverName,
                tools
            });
        } catch (error) {
            console.error(`获取服务器工具列表失败: ${serverName}`, error);
            this._view.webview.postMessage({
                command: 'error',
                message: `获取工具列表失败: ${error instanceof Error ? error.message : String(error)}`
            });
        }
    }

    /**
     * 添加新服务器
     */
    async _addServer() {
        if (!this._view) {
            return;
        }

        vscode.commands.executeCommand('mcp.addServer');
    }

    /**
     * 删除服务器
     */
    async _deleteServer(serverName) {
        if (!this._view) {
            return;
        }

        // 确认删除
        const result = await vscode.window.showWarningMessage(
            `确定要删除MCP服务器 "${serverName}" 吗?`,
            { modal: true },
            '删除',
            '取消'
        );

        if (result !== '删除') {
            return;
        }

        try {
            await this._mcpService.deleteServer(serverName);
            
            // 刷新服务器列表
            this._getServers();
            
            vscode.window.showInformationMessage(`已删除MCP服务器: ${serverName}`);
        } catch (error) {
            console.error(`删除MCP服务器失败: ${serverName}`, error);
            vscode.window.showErrorMessage(`删除服务器失败: ${error instanceof Error ? error.message : String(error)}`);
        }
    }

    /**
     * 启用/禁用服务器
     */
    async _toggleServer(serverName, enabled) {
        if (!this._view) {
            return;
        }

        try {
            await this._mcpService.toggleServer(serverName, enabled);
            
            // 刷新服务器列表
            this._getServers();
            
            vscode.window.showInformationMessage(
                `MCP服务器 ${serverName} 已${enabled ? '启用' : '禁用'}`
            );
        } catch (error) {
            console.error(`切换服务器状态失败: ${serverName}`, error);
            vscode.window.showErrorMessage(
                `更新服务器状态失败: ${error instanceof Error ? error.message : String(error)}`
            );
        }
    }

    /**
     * 设置工具自动批准
     */
    async _toggleToolAutoApprove(serverName, toolNames, autoApprove) {
        if (!this._view) {
            return;
        }

        try {
            await this._mcpService.toggleToolAutoApprove(serverName, toolNames, autoApprove);
            
            // 刷新工具列表
            this._getServerTools(serverName);
            
            vscode.window.showInformationMessage(
                `已${autoApprove ? '启用' : '禁用'}自动批准，影响了 ${toolNames.length} 个工具`
            );
        } catch (error) {
            console.error(`更新工具自动批准设置失败: ${serverName}`, error);
            vscode.window.showErrorMessage(
                `更新工具自动批准设置失败: ${error instanceof Error ? error.message : String(error)}`
            );
        }
    }

    /**
     * 更新服务器超时设置
     */
    async _updateServerTimeout(serverName, timeout) {
        if (!this._view) {
            return;
        }

        try {
            await this._mcpService.updateServerTimeout(serverName, timeout);
            
            // 刷新服务器列表
            this._getServers();
            
            vscode.window.showInformationMessage(
                `已更新MCP服务器 ${serverName} 的超时设置为 ${timeout} 秒`
            );
        } catch (error) {
            console.error(`更新服务器超时设置失败: ${serverName}`, error);
            vscode.window.showErrorMessage(
                `更新超时设置失败: ${error instanceof Error ? error.message : String(error)}`
            );
        }
    }

    /**
     * 更新MCP服务实例
     * @param {object} mcpService MCP服务实例
     */
    updateMcpService(mcpService) {
        this._mcpService = mcpService;
        if (this._view) {
            this._initViewData();
        }
    }
}

module.exports = { McpViewProvider }; 